import os
import re

from app.logic.utils.filepath import PATCH_DIR


class PatchAnalysis:
    def __init__(self, work_path_dir, project_path_dir):
        self.workspace = os.path.join(work_path_dir, str(project_path_dir))
        self.patch_dir = os.path.join(work_path_dir, str(project_path_dir), PATCH_DIR)

    # 获取 patch 文件夹下所有文件的内容中包含 .java 的文件名，并去重，返回文件名列表
    def get_java_references(self):
        java_references = set()  # 使用 set 自动去重
        java_pattern = re.compile(r'\b([\w-]+\.java)\b')  # 匹配不带路径的 .java 文件名

        for root, _, files in os.walk(str(self.patch_dir)):
            for file in files:
                file_path = os.path.join(root, file)
                with open(file_path, 'r', encoding='utf-8') as f:
                    for line in f:
                        matches = java_pattern.findall(line)  # 提取所有符合的文件名
                        java_references.update(matches)  # 加入集合

        return list(java_references)  # 将集合转换为列表返回

    # 获取 patch 文件夹下所有内容中 - 开头的语句，返回语句列表
    def get_removed_statements(self):
        removed_statements = []
        for root, _, files in os.walk(str(self.patch_dir)):
            for file in files:
                file_path = os.path.join(root, file)
                print(f"Loading patch file: {file_path}")
                with open(file_path, 'r', encoding='utf-8') as f:
                    for line in f:
                        stripped_line = line.strip()
                        if stripped_line.startswith('-') and not stripped_line.startswith('--'):
                            # 去掉开头的 '-' 并去除前后空格
                            removed_statements.append(stripped_line[1:].strip())
        return removed_statements

# if __name__ == '__main__':
#     work_dir = '../../../data'  # 请修改为实际路径
#     project_path = '31'  # 请修改为实际项目路径
#     patch_analysis = PatchAnalysis(work_dir, project_path)
#     java_references = patch_analysis.get_java_references()
#     removed_statements = patch_analysis.get_removed_statements()
#     print("java_references:", java_references)
#     print("len(java_references):", len(java_references))
#     print("removed_statements:", removed_statements)
#     print("len(removed_statements):", len(removed_statements))
